#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>

void writer(int wid)
{
    int cnt = 5;//写入5秒
    char* str = "Hello,child write success!";
    char buffer[1024];
    while(cnt--)
    {
        snprintf(buffer,1024,"%s pid:%d cnt:%d",str,getpid(),cnt);
        write(wid,buffer,strlen(buffer));
        sleep(1);
    }
}

void reader(int rid)
{
    int cnt = 5;//读取5秒
    char buffer[1024];
    while(cnt--)
    {
        read(rid,buffer,1024);
        printf("%s\n",buffer);
    }
    
}

int main()
{
    int pipefd[2];
    int n = pipe(pipefd);
    if(n < 0) return 1;
    pid_t id = fork();
    if(id == 0)
    {
        //child write
        //子进程写，关闭子进程读端
        close(pipefd[0]);
        writer(pipefd[1]);//writer函数使子进程不断向管道中写入数据
        exit(0);
    }
    //father read
    //父进程读，关闭父进程写端
    close(pipefd[1]);
    reader(pipefd[0]);//reader函数使父进程不断从管道中读取数据
    wait(NULL);
    return 0;
}